<template>
  <div :class="'zhzm-search-box ' + props.model">
    <el-popover :visible="isShowPopover" placement="bottom" :width="600">
      <div class="tipbox">
        <div v-for="(node, index) in tipResult.data" :key="(node as IndexDoc).id">
          <div class="title" :class="{ 'selected': index === selectedIndex }"
            @click="clickPopover((node as IndexDoc).title!)" v-html="(node as IndexDoc).title"></div>
        </div>
      </div>
      <template #reference>
        <div class="zhzm-inner-box">
          <el-icon style="color: #9aa0a6;margin-left: 20px;font-weight: 700;margin-right: 10px;">
            <Search />
          </el-icon>
          <input type="text" @keyup.enter="handleEnter" @keyup.up.prevent="handleArrowUp"
            @keyup.down.prevent="handleArrowDown" v-model="fomr.word" @focusout="showPopover(false, false)">
          <el-button style="margin-right: 4px;" type="danger" icon="Search" @click="doSearch" circle />
          <el-button style="margin-right: 10px;" type="warning" round @click="doSearchAi"><el-icon>
              <ChatDotRound />
            </el-icon>&nbsp;AI</el-button>
        </div>
      </template>
    </el-popover>
  </div>
</template>
<script setup lang="ts">
import type { IndexQuery } from '@/types/commons/IndexQuery';
import { reactive, ref, watch } from 'vue';
import cupk2Request from '@/service/remoteRequests/Cupk2Request';
import notice from '@/components/msg/CupkNotice';
import { RequestTypeEnum } from '@/types/commons/RequestTypeEnum';
import type { DataResponse } from '@/types/commons/DataResponse';
import type { DataResult } from '@/types/commons/DataResult';
import type { IndexDoc } from '@/types/commons/IndexDoc';
import cupkHtmlUtils from '@/hook/cupkHtmlUtils';
import { useRouter } from 'vue-router';
const router = useRouter();
const isShowPopover = ref(false);
const selectedIndex = ref(-1);
const fomr = reactive({
  word: ''
});
const props = defineProps({
  model: {
    type: String,
    required: true
  }
  ,
  doSearchHandle: {
    type: Function,
    required: true
  }
});
const tipResult = reactive({}) as DataResult;

let notLoadTip = true;


watch(
  () => fomr.word,
  () => {
    loadSearchTip();
  }
);
let isRequestloading = false;



const handleArrowUp = () => {
  if (tipResult.data!.length > 0) {
    selectedIndex.value = Math.max(0, selectedIndex.value - 1);
  }
};


const handleArrowDown = () => {
  if (tipResult.data!.length > 0) {
    selectedIndex.value = Math.min(tipResult.data!.length - 1, selectedIndex.value + 1);
  }
};


/**
 * 加载提示词
 */
const loadSearchTip = () => {
  if (notLoadTip) {
    notLoadTip = false;
    return;
  }
  if (!isRequestloading) {
    if (fomr.word && fomr.word.trim() !== "") {
      isRequestloading = true;
      cupk2Request.submit('api/search/title', RequestTypeEnum.post, null, { word: fomr.word }).then((response: DataResponse) => {
        Object.assign(tipResult, (response.data as DataResult))
        if (tipResult.totalSize > 0) {
          showPopover(true, false);
        } else {
          showPopover(false, false);
        }
        setTimeout(() => {
          isRequestloading = false;
        }, 2000);
      }).catch((msg: string) => {
        notice.byError(msg);
        setTimeout(() => {
          isRequestloading = false;
        }, 2000);
      });
    } else {
      showPopover(false, false);
    }
  }
};


/**
 * 点击提示词
 */
const clickPopover = (title: string) => {
  fomr.word = cupkHtmlUtils.removeHtmltags(title);
  showPopover(false, true);
}


const handleEnter = () => {
  if (selectedIndex.value >= 0 && selectedIndex.value < tipResult.data!.length) {
    const selectedTitle = cupkHtmlUtils.removeHtmltags((tipResult.data![selectedIndex.value] as IndexDoc).title!);
    fomr.word = selectedTitle;
    selectedIndex.value = -1;
    showPopover(false, true);
  } else {
    doSearch();
    showPopover(false, false);
  }

};

const showPopover = (isShow: boolean, theNotLoadTip: boolean) => {
  isShowPopover.value = isShow;
  notLoadTip = theNotLoadTip;
}

const doSearch = () => {
  props.doSearchHandle({ word: fomr.word, page: 1 } as IndexQuery);
}

const doSearchAi = () => {
  if (fomr.word) {
    router.push({ path: "/ai", query: { word: fomr.word } });
  }
}


const setWord = (word: string) => {
  fomr.word = word;
}
defineExpose({
  setWord
});


</script>
<style scoped>
/* 样式可以根据需要添加 */
.tipbox {
  padding: 10px;

  .title {
    padding: 8px;
    cursor: pointer;
  }
}

.title.selected {
  background-color: #e8f0fe;
  color: #1a73e8;
  font-weight: bold;
  border-radius: 4px;
}

.zhzm-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.zhzm-left {
  display: flex;
}

.zhzm-search-box .zhzm-inner-box {
  display: flex;
  align-items: center;
  height: 46px;
  width: 600px;
  min-width: 100px;
  border-radius: 24px;
  background-color: #ffffff;
  max-width: 600px;
  box-shadow: 0px 2px 8px 0px rgba(60, 64, 67, 0.25);
  padding: 4px;
}

.zhzm-search-box .zhzm-inner-box:hover {
  box-shadow: 0px 2px 8px 2px rgba(60, 64, 67, 0.25);
}

.zhzm-search-box .zhzm-inner-box input {
  outline: none;
  font-size: 16px;
  height: 90%;
  border: 0px;
  min-width: 50%;
  flex-grow: 1;
  padding-right: 20px;
  /* 新增：使 input 元素撑满剩余空间 */
}
</style>
